package cn.intotw.rdcj.core.config;

import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.io.IOException;

/**
 * Redisson配置类
 *
 * @author chenxiang
 * @create 2020年4月24日11:24:42
 */
@Configuration
public class RedissonConfig {

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private String port;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.database}")
    private int database;

    @Value("${spring.redis.connectTimeout}")
    private int connectTimeout;

    @Bean
    @Primary
    public RedissonClient redissonClient() throws IOException {
        Config config = new Config();
        // 若不设置密码，则密码设为null
        if(StringUtils.isBlank(password)) {
            password = null;
        }
        config.useSingleServer()
                //可以用"rediss://"来启用SSL连接
                .setAddress("redis://" + host + ":" + port)
                .setPassword(password)
                .setDatabase(database)
                .setConnectTimeout(connectTimeout);

        RedissonClient redisson = Redisson.create(config);
        return redisson;
    }

    /**使用纯字符串编码（无转换），可用于原子增减操作。*/
    @Bean
    public RedissonClient redisson4String() throws IOException {
        Config config = new Config();
        // 若不设置密码，则密码设为null
        if(StringUtils.isBlank(password)) {
            password = null;
        }
        config.useSingleServer()
                //可以用"rediss://"来启用SSL连接
                .setAddress("redis://" + host + ":" + port)
                .setPassword(password)
                .setDatabase(database)
                .setConnectTimeout(connectTimeout);

        return Redisson.create(config);
    }

}  